package com.cy.ppj.comm.handler;

import com.cy.ppj.model.enums.Process;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @description:
 * @author: Ocean
 * @create: 2018-08-03 14:13
 **/
@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ProcessArrTypeHandler extends BaseTypeHandler<List<Process>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Process> processes, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public List<Process> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getValue(resultSet.getString(s));
    }

    @Override
    public List<Process> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getValue(resultSet.getString(i));
    }

    @Override
    public List<Process> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getValue(callableStatement.getString(i));
    }

    private List<Process> getValue(String string) {
        List<Process> processList = new ArrayList<>();
        String[] arr = string.split(",");
        Stream.of(arr).forEach(p -> {
            Process process = Process.getProcess(p);
            processList.add(process);
        });
        return processList;
    }
}
